package pers.wk.utils;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

/**
 * MQ连接工具类
 */
public class MQConnectionUtils {

    //MQ管理页面的端口是15672

    //linux mq集群服务地址
//    private static final String host = "rabbitmq01";
//    private static final int port = 5671;

    //windows mq服务地址
    private static final String host = "101.43.135.185";
    private static final int port = 5672;


    private static final String userName = "admin";
    private static final String password = "123456";

    public static ConnectionFactory getConnectionFactory(String virtualHost) {
        //1.定义连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        //2.设置服务器地址
        factory.setHost(host);
        //3.设置协议端口号
        factory.setPort(port);
        //4.设置vhost
        factory.setVirtualHost(virtualHost);
        //5.设置用户名称
        factory.setUsername(userName);
        //6.设置用户密码
        factory.setPassword(password);
        //7.创建新的连接
        return factory;
    }

    /**
     * 关闭通道、连接
     *
     * @param connection
     * @param channel
     */
    public static void close(Connection connection, Channel channel) {
        if (channel != null && channel.isOpen()) {
            try {
                channel.close();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        // 7: 关闭连接
        if (connection != null && connection.isOpen()) {
            try {
                connection.close();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }
}
